# -*- coding: utf-8 -*-
# @File : .py
# @Author : ZhouHang
# @Date : 20-4-7
# @Desc :
from rest_framework import serializers
from django_redis import get_redis_connection


# url('^sms_codes/(?P<mobile>1[3-9]\d{9})/$', views.SMSCodeView.as_view()),
class ImageCodeCheckSerializer(serializers.Serializer):
    """
    图片验证码校验序列化器
    """
    # image_code_id = serializers.UUIDField()
    # text = serializers.CharField(max_length=4, min_length=4)
    #
    # def validate(self, attrs):
    #     """
    #     验证uuid 和图形验证码　发送短信
    #     :param attrs:
    #     :return:
    #     """
    #     image_code_id = attrs['image_code_id']
    #     text = attrs['text']
    #     # 根据request获取到的　图片id去redis中拿取验证码
    #     redis_conn = get_redis_connection('verify_codes')
    #     real_image_code_text = redis_conn.get('img_%s'%image_code_id)
    #     if real_image_code_text:
    #         # 应该在每次请求后删除原来的验证码　因为用户每次刷新或者点击图片都会有新的图形验证码
    #         redis_conn.delete('img_%s' % image_code_id)
    #         #　如果存在　表示拿到了　拿到了就和requert传过来的进行对比
    #         if real_image_code_text.decode().lower() == text:
    #             mobile = self.context['view'].kwargs['mobile']
    #             # 进行短信间隔时间验证
    #             send_flag = redis_conn.get('send_flag_%s'%mobile)
    #             if send_flag:
    #                 raise serializers.ValidationError('请求过于频繁,请稍后再请求')
    #             return attrs
    #
    #         else:
    #             raise serializers.ValidationError('图形验证失败')
    #
    #     else:
    #         raise serializers.ValidationError('图形验证码已过期')
    image_code_id = serializers.UUIDField()
    text = serializers.CharField(max_length=4, min_length=4)

    def validate(self, attrs):
        # print('*' * 50, 1)
        image_code_id = attrs['image_code_id']
        text = attrs['text']
        # print('*' * 50, 2)
        # 查询真实图片验证码
        redis_conn = get_redis_connection('verify_codes')
        real_image_code_text = redis_conn.get('img_%s' % image_code_id)
        if not real_image_code_text:
            raise serializers.ValidationError('图片验证码无效')

        # 删除redis中的图片验证码
        redis_conn.delete('img_%s' % image_code_id)

        # 比较图片验证码
        real_image_code_text = real_image_code_text.decode()
        if real_image_code_text.lower() != text.lower():
            raise serializers.ValidationError('图片验证码错误')

        # 判断是否在60s内
        # get_serializer 方法在创建序列化器对象的时候，会补充context属性
        # context 属性中包含三个值 request   format  view 类视图对象
        #  self.context['view']

        # django的类视图对象中，kwargs属性保存了路径提取出来的参数
        print('*' * 50, 3)
        mobile = self.context['view'].kwargs['mobile']

        send_flag = redis_conn.get("send_flag_%s" % mobile)
        if send_flag:
            raise serializers.ValidationError('请求次数过于频繁')

        return attrs

